import React, { useEffect, useState } from 'react';
import {
  menuTreeNodeFetch,
  menuUserTreeNodeFetch,
  CheckedUserRolesFetch,
  CheckedUserPermsFetch,
  userPermsSave,
} from '@/services/sysInfo';
import { message, Row, Col, Tree, Button, Modal, Spin, Alert } from 'antd';
import { Card } from 'antd';
import styles from './Users.css';
import DataEdit from '@/components/base/DataEdit';
import { fetchAll } from '@/services/commCRUD';
import { useModel } from 'umi';

import PageHeader from '@/components/page/PageHeader';
import _ from 'lodash';

const daoName = 'Role';
const TreeNode = Tree.TreeNode;
const UserPopedom: React.FC = () => {
  const [userID, setUserID] = useState<number>(-1);
  const [roleVal, setroleVal] = useState<string>('');
  const [userVal, setuserVal] = useState<string>('');
  const [roleDatas, setRoleDatas] = useState<Record<string, any>[]>([]);
  const [permTreeNodes, setpermTreeNodes] = useState<API.TreeNode[]>([]);
  const [UserTreeNodes, setUserTreeNodes] = useState<API.TreeNode[]>([]);
  const [permUserCheckedKeys, setPermUserCheckedKeys] = useState<string[]>([]);
  const [roleTreeCheckedKeys, setRoleTreeCheckedKeys] = useState<string[]>([]);
  const { bodyHeight } = useModel('sysInfo');

  useEffect(() => {
    const seeks: string = _.isEmpty(roleVal) ? '' : `RoleName like '%${roleVal}%'`;
    fetchAll(
      daoName,
      [
        {
          FieldName: 'SortNo',
          Direction: 'ASC',
        },
      ],
      seeks,
    )
      .then(function (data) {
        if (data.length > 0) {
          setRoleDatas(data);
        } else {
          message.info('未找到搜索的信息。');
        }
      })
      .catch(function (ex) {
        console.error('请求角色错误', ex);
      });

    menuTreeNodeFetch()
      .then(function (data) {
        setpermTreeNodes(data);
      })
      .catch(function (ex) {
        console.error('请求菜单错误', ex);
      });
    const u: string = _.isEmpty(userVal) ? '' : userVal;
    menuUserTreeNodeFetch(u)
      .then(function (data) {
        if (data.length > 0) {
          setUserTreeNodes(data);
        } else {
          message.info('未找到搜索的信息。');
        }
      })
      .catch(function (ex) {
        console.error('请求员工错误', ex);
      });
  }, [roleVal, userVal]);
  useEffect(() => {
    if (userID === -1) {
      return;
    }
    CheckedUserPermsFetch(userID)
      .then(function (data) {
        setPermUserCheckedKeys(data);
      })
      .catch(function (ex) {
        console.error('请求员工权限错误', ex);
      });
    CheckedUserRolesFetch(userID)
      .then(function (data) {
        setRoleTreeCheckedKeys(data);
      })
      .catch(function (ex) {
        console.error('请求员工角色错误', ex);
      });
  }, [userID]);
  const onSelect = (selectedKeys: string[]) => {
    if (selectedKeys.length === 0) {
      return;
    }
    const sel = selectedKeys[0].substring(0, 1);
    let uID = -1;
    if (sel === 'u') {
      uID = Number(selectedKeys[0].substring(2, selectedKeys[0].length));
    }
    setUserID(uID);
  };
  const userSubmit = () => {
    const userkey = 'u:' + userID;
    let userName = '';
    for (let i = 0; i < UserTreeNodes.length; i++) {
      if (userName === '') {
        for (let j = 0; j < UserTreeNodes[i].children.length; j++) {
          if (UserTreeNodes[i].children[j].children !== null) {
            for (let k = 0; k < UserTreeNodes[i].children[j].children.length; k++) {
              if (UserTreeNodes[i].children[j].children[k].key === userkey) {
                userName = UserTreeNodes[i].children[j].children[k].title;
                break;
              }
            }
          } else {
            if (UserTreeNodes[i].children[j].key === userkey) {
              userName = UserTreeNodes[i].children[j].title;
              break;
            }
          }
        }
      } else {
        break;
      }
    }
    Modal.confirm({
      title: '提示',
      content: `你确认授予用户${userName}权限吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        userPermsSave(userID, permUserCheckedKeys, roleTreeCheckedKeys)
          .then(function (data: string) {
            if (data === 'OK') {
              message.success('权限保存成功！');
            }
          })
          .catch(function (ex) {
            console.log(ex.toString());
          });
      },
    });
  };
  const clearUser = () => {
    const userkey = 'u:' + userID;
    let userName = '';
    for (let i = 0; i < UserTreeNodes.length; i++) {
      if (userName === '') {
        for (let j = 0; j < UserTreeNodes[i].children.length; j++) {
          if (UserTreeNodes[i].children[j].children !== null) {
            for (let k = 0; k < UserTreeNodes[i].children[j].children.length; k++) {
              if (UserTreeNodes[i].children[j].children[k].key === userkey) {
                userName = UserTreeNodes[i].children[j].children[k].title;
                break;
              }
            }
          } else {
            if (UserTreeNodes[i].children[j].key === userkey) {
              userName = UserTreeNodes[i].children[j].title;
              break;
            }
          }
        }
      } else {
        break;
      }
    }

    Modal.confirm({
      title: '提示',
      content: `你确认清空用户${userName}的所有权限吗？`,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        userPermsSave(userID, [], [])
          .then(function (data: string) {
            if (data === 'OK') {
              setPermUserCheckedKeys([]);
              setRoleTreeCheckedKeys([]);
              message.success('权限清空成功！');
            }
          })
          .catch(function (ex) {
            message.error(ex.toString());
          });
      },
    });
  };
  const submitFindRole = async (vals: Record<string, any>) => {
    if (_.isEmpty(vals.name)) {
      message.error('请输入搜索的字符');
      return;
    }
    setroleVal(vals.name);
  };
  const submitFindUser = async (vals: Record<string, any>) => {
    if (_.isEmpty(vals.name)) {
      message.error('请输入搜索的所属部门/用户');
      return;
    }
    setuserVal(vals.name);
  };
  const controlsRole: API.Control[] = [
    {
      name: 'name',
      label: '',
      type: 'text',
      grid: 12 / 24,
      width: 200,
      placeholder: '请输入部门用户',
    },
  ];
  const controlsUser: API.Control[] = [
    {
      name: 'name',
      label: '',
      type: 'text',
      grid: 12 / 24,
      width: 200,
      placeholder: '请输入部门用户',
    },
  ];
  if (roleDatas.length === 0 || permTreeNodes.length === 0 || UserTreeNodes.length === 0) {
    return (
      <Spin tip="页面加载中...">
        <Alert message="角色权限设置" description="页面正在加载中，请您稍等..." type="info" />
      </Spin>
    );
  } else {
    const key = UserTreeNodes[0].key;
    const loopR = (treeDatas: any[]) =>
      treeDatas.map((item) => {
        if (item.children) {
          return (
            <TreeNode key={item.ID} title={item.Name}>
              {loopR(item.children)}
            </TreeNode>
          );
        }
        return <TreeNode key={item.ID} title={item.Name} />;
      });
    const loop = (tNodes: API.TreeNode[]) =>
      tNodes.map((item) => {
        if (item.children) {
          return (
            <TreeNode key={item.key} title={item.title}>
              {loop(item.children)}
            </TreeNode>
          );
        }
        return <TreeNode key={item.key} title={item.title} />;
      });
    const loopU = (tNodes: API.TreeNode[]) =>
      tNodes.map((item) => {
        if (item.children) {
          return (
            <TreeNode key={item.key} title={item.title}>
              {loopU(item.children)}
            </TreeNode>
          );
        }
        return <TreeNode key={item.key} title={item.title} />;
      });
    return (
      <PageHeader>
        <div className={styles.normal}>
          <Row>
            <Col span={8} style={{ paddingRight: 15 }}>
              <Card title="所属部门用户" bordered={false}>
                <DataEdit
                  showType="inner"
                  layout="inline"
                  grid={false}
                  onSumit={submitFindUser}
                  controls={controlsUser}
                  renderButtons={(p) => {
                    return [
                      <Button type="primary" key="find" onClick={() => p.form?.submit?.()}>
                        搜索
                      </Button>,
                      <Button type="primary" key="reset" onClick={() => setuserVal('')}>
                        重置
                      </Button>,
                    ];
                  }}
                />
                <div style={{ height: bodyHeight - 280, overflow: 'auto', background: '#fff' }}>
                  <Tree
                    onSelect={(keys) => onSelect(keys as string[])}
                    // defaultExpandedKeys={[key]}
                  >
                    {loopU(UserTreeNodes)}
                  </Tree>
                </div>
              </Card>
            </Col>
            <Col span={8} style={{ paddingRight: 15 }}>
              <Card title="功能菜单" bordered={false}>
                <div style={{ height: bodyHeight - 280, overflow: 'auto', background: '#fff' }}>
                  <Tree
                    checkable
                    onCheck={(keys) => setPermUserCheckedKeys(keys as string[])}
                    checkedKeys={permUserCheckedKeys}
                  >
                    {loop(permTreeNodes)}
                  </Tree>
                </div>
              </Card>
              <Row style={{ marginTop: 10 }}>
                <Col span={12}>
                  <span style={{ float: 'right', marginRight: 10 }}>
                    <Button type="primary" onClick={userSubmit}>
                      保存
                    </Button>
                  </span>
                </Col>
                <Col span={12}>
                  <span style={{ float: 'left', marginLeft: 10 }}>
                    <Button type="primary" onClick={clearUser}>
                      清除
                    </Button>
                  </span>
                </Col>
              </Row>
            </Col>
            <Col span={8}>
              <Card title="角色" bordered={false}>
                <DataEdit
                  showType="inner"
                  layout="inline"
                  grid={false}
                  onSumit={submitFindRole}
                  controls={controlsRole}
                  renderButtons={(p) => {
                    return [
                      <Button type="primary" key="find" onClick={() => p.form?.submit?.()}>
                        搜索
                      </Button>,
                      <Button type="primary" key="reset" onClick={() => setroleVal('')}>
                        重置
                      </Button>,
                    ];
                  }}
                />
                <div style={{ height: bodyHeight - 280, overflow: 'auto', background: '#fff' }}>
                  <Tree
                    checkable
                    onCheck={(keys) => setRoleTreeCheckedKeys(keys as string[])}
                    checkedKeys={roleTreeCheckedKeys}
                  >
                    {loopR(roleDatas)}
                  </Tree>
                </div>
              </Card>
            </Col>
          </Row>
        </div>
      </PageHeader>
    );
  }
};
export default UserPopedom;
